﻿using SmartSapce.ServiceLocation;
using SmartSpace.OA;
using SmartSpace.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Workflow;
using SmartSpace.Core;

namespace SmartSpace.WebApp.Modules.OA.Pages
{
    public partial class LeaveRequest_Create : SsTemplatePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                _ctlEditCreator.Text = User.Identity.Name;

                ICoreService service = ServiceLocator.Get<ICoreService>();
                List<CodeDefinition> codes = service.GetCodeDefinitions("OA.LEAVETYPE");
                _ctlListType.DataSource = codes;
                _ctlListType.DataBind();
            }
        }

        protected void _ctlBtnSave_Click(object sender, EventArgs e)
        {
            LeaveRequest request = new LeaveRequest();
            request.Id = Guid.NewGuid();
            request.Subject = _ctlEditSubject.Text;
            request.Description = _ctlEditDescription.Text;
            request.TypeCode = this._ctlListType.SelectedValue;
            request.TypeCaption = this._ctlListType.SelectedItem.Text;
            request.CreatedDate = DateTime.Now;
            request.Creator = this.User.Identity.Name;
            request.CreatorName = this.User.Identity.Name;

            request.StartTime = Convert.ToDateTime(_ctlEditStartDate.Text);
            request.EndTime = Convert.ToDateTime(this._ctlEditEndDate.Text);

            ILeaveService service = ServiceLocator.Get<ILeaveService>();
            if (service.Save(request).IsSuccess)
            {
                IWorkflowService wfService = ServiceLocator.Get<IWorkflowService>();
                SingleResult<InstanceState> state = wfService.CreateInstance("OA.LEAVE", request.Id, request.Subject, request.Creator);
                
                Response.Redirect("LeaveRequest-List.aspx");
            }
        }
    }
}